package com.zhuo.common.service.tencent;

import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import com.zhuo.common.config.StsProperties;
import com.zhuo.common.domain.sts.StsCredential;
import com.zhuo.common.exception.StsException;
import com.zhuo.common.service.StsService;

import java.time.Instant;
import java.util.TreeMap;

/**
 * 腾讯cosSts实现类
 */
public class TencentCosStsService implements StsService {

    private final StsProperties stsProperties;
    private final TencentCosProperties tencentCosProperties;

    public TencentCosStsService(StsProperties stsProperties, TencentCosProperties tencentCosProperties) {
        this.stsProperties = stsProperties;
        this.tencentCosProperties = tencentCosProperties;
    }

    @Override
    public StsCredential getStsCredential() throws StsException {
        TreeMap<String, Object> config = new TreeMap<>();
        try {
            // 密钥对
            config.put("secretId", tencentCosProperties.getSecretId());
            config.put("secretKey", tencentCosProperties.getSecretKey());
            // 临时密钥有效时长，单位是秒，默认 1800 秒，目前主账号最长 2 小时（即 7200 秒），子账号最长 36 小时（即 129600）秒
            config.put("durationSeconds", stsProperties.getExpireSeconds());
            // 桶名称
            config.put("bucket", tencentCosProperties.getBucketName());
            // 所在地区
            config.put("region", tencentCosProperties.getRegion());
            // 允许的路径前缀
            config.put("allowPrefixes", stsProperties.getAllowPrefix());
            // 密钥的权限列表
            config.put("allowActions", stsProperties.getAllowActions());

            // 申请密钥对
            Response response = CosStsClient.getCredential(config);

            // result
            StsCredential result = new StsCredential();
            result.setTmpSecretId(response.credentials.tmpSecretId);
            result.setTmpSecretKey(response.credentials.tmpSecretKey);
            result.setSessionToken(response.credentials.sessionToken);
            result.setStartTime(Instant.now().getEpochSecond());
            result.setExpiredTime(response.expiredTime);
            result.setRegion(tencentCosProperties.getRegion());
            result.setBucketName(tencentCosProperties.getBucketName());

            return result;
        } catch (IllegalArgumentException e) {
            throw new StsException("配置错误，请检查 SecretId/SecretKey", e);
        } catch (Exception e) {
            throw new StsException("腾讯COS临时凭证获取失败", e);
        }
    }
}
